CISC 1110             Lab 18a Linear Sort

 

     Here is the basic linear sort code:

 

for (int pos = 0; pos < n - 1; pos++)

    for (int cand = pos + 1; cand < n; cand++)

         if (numb[pos] > numb[cand]) {

             // switch 'em

             temp = numb[pos];

             numb[pos] = numb[cand];

             numb[cand] = temp;

         }

 

   Turn this code into a function, linearsort, which receives 2 parameters: numb, an array of integers and n, the number of filled positions in the array. You will need to add the declaration for temp.

 

    In the main program, declare an array and initialize it in the declaration, like this:

 

int vals[10] = {list of values here...separated by commas};

 

Give the array at least 7 values; make sure the values are not in order, either ascending or descending. Make two values the same. Initialize n to the number of filled positions in the array.

 

            Call the linearsort function, sending it vals and n. In main, print the array after returning from linearsort.

 

a. Run the program and see that it sorts the array.

 

     Now make the following changes and see what happens in each case:

 

b. Try to interchange two items using these two statements inside the brackets { } (instead of the three shown above).  What happens? Why?

 

     numb[pos] = numb[cand];

     numb[cand] = numb[pos];

 

 

 

b. Try to use the following for loops for the linear sort (do you see what is different), instead of what is shown above. What happens? Why?

 

for (int pos = 0; pos < n - 1; pos++)

    for (int cand = 0; cand < n; cand++)

 

 

 

c. Try to use the following if condition to compare two items [instead of if (numb[pos] > numb[cand]) ].  What happens? Why?

 

        if (pos > cand) {